<script setup lang="ts">
import type { FormInstance } from 'element-plus'
import { ElMessage } from 'element-plus'
// import qs from 'qs'
import type { FormType } from './index'
import { GetDataDetail, PostCreateData, PutModifyData } from '@/api/modules/shop'
import detailStore from '@/store/modules/cacheData'

const router = useRouter()
const route = useRoute()
const detailData = detailStore()

const id = route.query.id as string

const ruleFormRef = ref<FormInstance>()
const ruleForm = ref<FormType>({
  shopName: '',
  shopPic: '',
  shopAddress: '',
  phone: '',
  shopStatus: 1,
  desp: '',
  realName: '',
  userStatus: 1,
  userMobile: '',
  faceUrl: '',
  percents: 0,
})

const rules = reactive({
  userId: [
    { required: true, message: '请选择店长用户ID', trigger: 'blur' },
  ],
  realName: [
    { required: true, message: '请输入店长真实姓名', trigger: 'blur' },
  ],
  userStatus: [
    { required: true, message: '请选择账户状态', trigger: 'blur' },
  ],
  shopName: [
    { required: true, message: '请输入店铺名称', trigger: 'blur' },
  ],
  shopPic: [
    { required: true, message: '请上传店铺图片', trigger: 'blur' },
  ],
  shopAddress: [
    { required: true, message: '请输入店铺地址', trigger: 'blur' },
  ],
  phone: [
    { required: true, message: '请输入电话', trigger: 'blur' },
  ],
  shopStatus: [
    { required: true, message: '请选择店铺状态', trigger: 'blur' },
  ],
  userMobile: [
    { required: true, message: '请填写店长手机号', trigger: 'blur' },
  ],
})

// 提交
async function SubmitData(formEl: FormInstance | undefined) {
  if (!formEl) {
    return
  }
  await formEl.validate((valid) => {
    if (valid) {
      const params = { ...ruleForm.value }

      if (id) {
        // 编辑
        PutModifyData(params).then((res: any) => {
          if (res.statusCode === 200) {
            ElMessage.success('编辑成功')
            router.push({ name: 'shopIndex' })
          }
          else {
            if (typeof res.errors === 'string') {
              ElMessage.error(`编辑失败。${res.errors}`)
            }
            else {
              let errorStr = ''
              for (const key in res.errors) {
                errorStr += `${key}：${res.errors[key]}；`
              }
              ElMessage.error(`编辑失败。${errorStr}`)
            }
          }
        })
      }
      else {
        // 添加
        PostCreateData(params).then((res: any) => {
          if (res.statusCode === 200) {
            ElMessage.success('添加成功')
            detailData.EmptyShop()
            router.push({ name: 'shopIndex' })
          }
          else {
            ElMessage.error(`添加失败。${res.errors}`)
          }
        })
      }
    }
    else {
      ElMessage.error('请检查表单')
    }
  })
}

function handleUploadSuccess(urls: string, key: any) {
  if (urls) {
    // eslint-disable-next-line ts/ban-ts-comment
    // @ts-expect-error
    ruleForm.value[key] = urls
  }
}

// 筛选店长ID
// const OpenIdOptionList = ref([])
// const total = ref(0)

// const findFrom = ref({
//   UserId: '',
//   SCOpenId: '',
//   UserPhone: '',
//   UserNickName: '',
// })
// function GetUserIdOptionList(PageIndex: number = 1, PageSize: number = 20) {
//   const params = {
//     PageIndex,
//     PageSize,
//     ...(findFrom.value.UserId && ({ UserIdList: [findFrom.value.UserId] })),
//     ...(findFrom.value.SCOpenId && ({ SCOpenId: findFrom.value.SCOpenId })),
//     ...(findFrom.value.UserPhone && ({ UserPhone: findFrom.value.UserPhone })),
//     ...(findFrom.value.UserNickName && ({ UserNickName: findFrom.value.UserNickName })),
//     IsAuth: true,
//   }
//   const parameter = qs.stringify(params)
//   GetUserID(parameter).then((res: any) => {
//     if (res.statusCode === 200) {
//       OpenIdOptionList.value = res.data.items
//       total.value = res.data.total
//     }
//     else {
//       ElMessage.error(`获取数据失败。${res.errors}`)
//     }
//   })
// }

// function SetData(userId: number) {
//   ruleForm.value.userId = userId
// }

// function GetUserIdData() {
//   GetUserIdOptionList()
// }

// 翻页
// let PageSize = 20
// function handleSizeChange(val: number) {
//   GetUserIdOptionList(1, val)
//   PageSize = val
// }
// function handleCurrentChange(val: number) {
//   GetUserIdOptionList(val, PageSize)
// }

watch(ruleForm, (newValue) => {
  if (!id) {
    detailData.RememberShop(newValue)
  }
}, { deep: true })

onMounted(async () => {
  if (id) {
    await GetDataDetail(id).then((res: any) => {
      if (res.statusCode === 200) {
        ruleForm.value = res.data
      }
    })
  }
  else {
    ruleForm.value = detailData.GetShop()
  }

  // GetUserIdData()
})
</script>

<template>
  <div>
    <PageHeader :title="id ? '编辑' : '添加'" />
    <ElForm ref="ruleFormRef" label-position="top" label-width="80px" :rules="rules" :model="ruleForm">
      <PageMain title="店铺信息">
        <ElRow :gutter="20">
          <ElCol :md="8">
            <ElFormItem label="店铺名称" prop="shopName">
              <el-input v-model="ruleForm.shopName" style="width: 300px;" placeholder="请输入店铺名称" />
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="店铺地址" prop="shopAddress">
              <el-input v-model="ruleForm.shopAddress" style="width: 300px;" placeholder="请输入店铺地址" />
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="店铺电话" prop="phone">
              <el-input v-model="ruleForm.phone" style="width: 300px;" placeholder="请输入电话" type="number" />
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="店铺状态" prop="shopStatus">
              <el-radio-group v-model="ruleForm.shopStatus">
                <el-radio :value="1">
                  正常
                </el-radio>
                <el-radio :value="2">
                  冻结
                </el-radio>
              </el-radio-group>
            </ElFormItem>
          </ElCol>
          <ElCol :md="24">
            <ElFormItem label="描述">
              <el-input v-model="ruleForm.desp" style="max-width: 550px;" placeholder="请输入描述" type="textarea" />
            </ElFormItem>
          </ElCol>
          <ElCol :md="24">
            <ElFormItem label="上传店铺图片" prop="shopPic">
              <ImageUpload width="auto" :ext="['jpg', 'png']" :size="5" :max="1" :url="ruleForm.shopPic" @on-success="(url) => handleUploadSuccess(url, 'shopPic')" />
            </ElFormItem>
          </ElCol>
        </ElRow>
      </PageMain>
      <!-- <PageMain title="筛选店长ID">
        <ElRow :gutter="20">
          <ElCol :md="5">
            <ElFormItem label="用户ID">
              <el-input v-model="findFrom.UserId" style="width: 300px;" placeholder="请输入用户ID" />
            </ElFormItem>
          </ElCol>
          <ElCol :md="5">
            <ElFormItem label="OpenId">
              <el-input v-model="findFrom.SCOpenId" style="width: 300px;" placeholder="请输入OpenId" />
            </ElFormItem>
          </ElCol>
          <ElCol :md="5">
            <ElFormItem label="微信昵称">
              <el-input v-model="findFrom.UserNickName" style="width: 300px;" placeholder="请输入微信昵称" />
            </ElFormItem>
          </ElCol>
          <ElCol :md="5">
            <ElFormItem label="授权手机号">
              <el-input v-model="findFrom.UserPhone" style="width: 300px;" placeholder="请输入授权手机号" />
            </ElFormItem>
          </ElCol>
          <ElCol :md="4">
            <ElFormItem label="操作">
              <ElButton @click="GetUserIdData">
                查询
              </ElButton>
            </ElFormItem>
          </ElCol>
          <ElCol :md="24">
            <el-table :data="OpenIdOptionList" stripe style="width: 100%;" border height="400">
              <el-table-column align="center" prop="userId" label="userId" width="150" />
              <el-table-column align="center" prop="scOpenId" label="OpenId" min-width="350" />
              <el-table-column align="center" prop="userNickName" label="微信昵称" width="300" />
              <el-table-column align="center" prop="userPhone" label="授权手机号" width="200" />
              <el-table-column align="center" prop="address" label="操作" fixed="right" min-width="100">
                <template #default="scope">
                  <ElButton type="primary" @click="SetData(scope.row.userId)">
                    应用
                  </ElButton>
                </template>
              </el-table-column>
            </el-table>
            <div style="height: 10px;" />
            <el-pagination
              :default-page-size="20"
              :page-sizes="[5, 10, 20, 50, 100]"
              layout="total, sizes, ->, prev, pager, next, jumper"
              :total="total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </elcol>
        </elrow>
      </PageMain> -->
      <PageMain title="店长信息">
        <ElRow :gutter="20">
          <ElCol :md="8">
            <ElFormItem label="店长真实姓名" prop="realName">
              <el-input v-model="ruleForm.realName" style="width: 300px;" placeholder="请输入店长真实姓名" />
            </ElFormItem>
          </ElCol>
          <!-- <ElCol :md="8">
            <ElFormItem label="店长用户ID" prop="userId">
              <el-input v-model="ruleForm.userId" style="width: 300px;" placeholder="请输入店长用户ID" />
            </ElFormItem>
          </ElCol> -->
          <ElCol :md="8" prop="userMobile">
            <ElFormItem label="店长手机号" prop="userMobile">
              <el-input v-model="ruleForm.userMobile" style="width: 300px;" placeholder="请输入店长手机号" type="number" />
            </ElFormItem>
          </ElCol>
          <!-- <ElCol :md="8">
            <ElFormItem label="店长分润百分比">
              <el-input v-model="ruleForm.percents" style="width: 300px;" placeholder="请输入店长分润百分比" type="number" />
            </ElFormItem>
          </ElCol> -->
          <ElCol :md="8">
            <ElFormItem label="账户状态" prop="userStatus">
              <el-radio-group v-model="ruleForm.userStatus">
                <el-radio :value="1">
                  启用
                </el-radio>
                <el-radio :value="2">
                  冻结
                </el-radio>
              </el-radio-group>
            </ElFormItem>
          </ElCol>
          <!-- <ElCol :md="24">
            <ElFormItem label="店长头像（不传或者传空时应用用户授权头像）">
              <ImageUpload :ext="['jpg', 'png']" :size="5" :max="1" :url="ruleForm.faceUrl" @on-success="(url) => handleUploadSuccess(url, 'faceUrl')" />
            </ElFormItem>
          </ElCol> -->
        </ElRow>
      </PageMain>
    </ElForm>
    <div style="height: 80px;" />
    <FixedActionBar>
      <ElButton type="primary" size="large" @click="SubmitData(ruleFormRef)">
        提交
      </ElButton>
    </FixedActionBar>
  </div>
</template>

<style lang="scss" scoped>
.box {
  .title {
    display: flex;
    justify-content: space-between;
    margin-bottom: 10px;
  }
}

.card-box {
  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-gap: 10px;
}
</style>
